Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Add Relation::getMorphAlias() #51809

Merged
merged 2 commits into from
Jun 17, 2024

Conversation

pxlrbt
Copy link
Contributor

@pxlrbt pxlrbt commented Jun 15, 2024

Since there is a Relation::getMorphedModel() I think it would be beneficial to add the reverse getMorphAlias.

This addition is particularly beneficial for testing, as it simplifies assertions with $this->assertDatabaseHas. Developers no longer need to recall the morph alias used:

$this->assertDatabaseHas('taskables', [
   'taskable_type' => Relation::getMorphAlias(Document::class),
   'taskable_id' => $mitigation->id,
   'task_id' => $taskB->id
]);

A similar PR with a broader scope was previously submitted:
#43487

@pxlrbt pxlrbt changed the title [11.x] Add Relation::getMorphAlias [11.x] Add Relation::getMorphAlias() Jun 15, 2024
@taylorotwell taylorotwell merged commit 9c19eb8 into laravel:11.x Jun 17, 2024
28 checks passed
@pxlrbt pxlrbt deleted the feature/relation-get-morph-alias branch June 17, 2024 21:18
*/
public static function getMorphAlias(string $className)
{
return array_flip(static::$morphMap)[$className] ?? null;
Copy link
Contributor

@Tofandel Tofandel Jun 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this have been array_search($className, static::$morphMap) ?: $className

array_search performs about 3 times better in this kind of configuration than array_flip

https://onlinephp.io/c/43ff4

Why return null and not the original class name?

This makes the example in the description much more verbose now and not a drop in replacement for $model->getMorphClass()

$this->assertDatabaseHas('taskables', [
   'taskable_type' => Relation::getMorphAlias(Document::class) ?? Document::class,
   'taskable_id' => $mitigation->id,
   'task_id' => $taskB->id
]);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: #51845

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @calebdw for improving this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants